package jpf.nextsearch.util.validation.base;

import jpf.nextsearch.base.GenericObject;
import jpf.nextsearch.util.validation.ValidationTypes;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @author <a href="mailto:jacek.pruszkowski@gmail.com">Jacek Pruszkowski</a>
 */
public abstract class AbstractFormValidator extends GenericObject 
		implements Validator {
	
	/** 
	 * domyslny komunikat z bledem - gdy sie pojawi oznacza ze brakuje
	 * odpowiedniego komunikatu w pliku properties
	 * 
	 */
	protected static final String DEFAUL_ERROR_MSG = "ERROR !"; 
	
	private ValidatorManager validatorManager;
	
	private Class<?> commandClass;
	
	protected AbstractFormValidator(Class<?> klass) {
		this.commandClass = klass;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class klass) {
		return commandClass.equals(klass);
	}
	protected boolean validate(String value, String fieldName,
			String validationType, boolean mandatory, String emptyMsg,
			String invalidMsg, Errors errors) {
		return this.validate((Object) value, fieldName, validationType,
			mandatory, emptyMsg, invalidMsg, errors);
	}
	
	protected boolean validate(Object value, String fieldName, String validationType,
			boolean mandatory, String emptyMsg, String invalidMsg, Errors errors) {
		if (!mandatory) {
			if (getValidatorManager().isValueValid(value, ValidationTypes.EMPTY)) {
				if (isLoggingDebug()) {
					getLogger().debug("not mandatory field ["+fieldName+"] is empty -> OK");
				}
				return true;
			}
		} else if (!getValidatorManager().isValueValid(value, ValidationTypes.NOT_EMPTY)) {
			if (isLoggingDebug()) {
				getLogger().debug("mandatory field ["+fieldName+"] is empty -> ERROR");
			}
			errors.rejectValue(fieldName, emptyMsg, null, DEFAUL_ERROR_MSG);
			return false;
		}
		if (validationType == null) {
			if (isLoggingDebug()) {
				getLogger().debug("validation type for field ["+fieldName
					+"] is empty -> no validation");
			}
			return true;
		}
		if (!getValidatorManager().isValueValid(value, validationType)) {
			if (isLoggingDebug()) {
				getLogger().debug("validation ["+validationType+"] for field ["+fieldName+"] failed -> ERROR");
			}
			errors.rejectValue(fieldName, invalidMsg, null, DEFAUL_ERROR_MSG);
			return false;
		}
		if (isLoggingDebug()) {
			getLogger().debug("validation ["+validationType+"] for field ["+fieldName+"] passed -> OK");
		}
		return true;
	}
	
	public void setValidatorManager(ValidatorManager validatorManager) {
		this.validatorManager = validatorManager;
	}
	
	public ValidatorManager getValidatorManager() {
		return validatorManager;
	}
}
